const {
    sleep,
    logger,
    httpGet,
    syncExec,
    readCookieFromFile,
} = require('./model'); 

//调试用的规格，上线后设置为空字符串
const debugSerial = '';
//调试限定数量，上线后设置为0
const debugNum = 0;

//拉取任务地址
const fetchTask = 'http://wafer.shenzhenbenwo.com/api/Tiserial/fetch';

(async () => {

    let serial;
    let url;
    let ret;
    let retJson;

    while (1) {
        //读取新任务
        if (debugSerial) {
            serial = debugSerial;
        } else {
            try {
                ret = await httpGet(fetchTask);
                retJson = JSON.parse(ret.body);
                if (!retJson.serial) continue;
                serial = retJson.serial;
            } catch(e) {
                await sleep(2000);
                continue;
            }
        }

        if (debugNum > 0) {
            stock = debugNum;
        } else {
            logger(serial, '获取商品库存数量');
            url = 'https://www.ti.com.cn/storeservices/cart/opninventory?opn='+encodeURIComponent(serial);
            try {
                ret = await httpGet(url);
                retJson = JSON.parse(ret.body);
                stock = retJson.inventory;
                logger(serial, '库存数', stock);
                await sleep(2000);
            } catch(e) {
                logger('获取商品库存失败', e);
                await sleep(2000);
                continue;
            }
        }

        //加购物车
        logger(serial, '加购物车');
        const cookie = await readCookieFromFile();
        const cmdStr = `curl --compressed \
        -H 'Host: www.ti.com.cn' \
        -H 'Connection: keep-alive' \
        -H 'sec-ch-ua: "Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"' \
        -H 'sec-ch-ua-mobile: ?0' \
        -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36" \
        -H "Content-Type: application/json" \
        -H 'X-Sec-Clge-Req-Type: ajax' \
        -H 'Expires: 0' \
        -H "Cache-Control: no-store, must-revalidate" \
        -H 'sec-ch-ua-platform: "macOS"' \
        -H 'Accept: */*' \
        -H 'Origin: https://www.ti.com.cn' \
        -H 'Sec-Fetch-Site: same-origin' \
        -H 'Sec-Fetch-Mode: cors' \
        -H 'Sec-Fetch-Dest: empty' \
        -H 'Referer: https://www.ti.com.cn/ordering-resources/buying-tools/quick-add-to-cart.html' \
        -H 'Accept-Encoding: gzip, deflate, br' \
        -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' \
        -H 'Cookie: ${cookie}' \
        -d '{"cartRequestList":[{"packageOption":null,"opnId":"${serial}","quantity":"${stock}","tiAddtoCartSource":"store-pdp","sparam":""}],"currency":"CNY"}' \
        https://www.ti.com.cn/occservices/v2/ti/addtocart -v`;

        ret = await syncExec(cmdStr);
        if (ret.indexOf('Access Denied') > -1) {
            logger('加购物车失败');
        } else if (ret.indexOf('cartId') > -1) {
            logger('加购物车成功');
        } else {
            logger('未知结果', ret);
        }
        await sleep(60000);
    }

})();
